<template>
	<div>
	
	</div>
</template>

<script>
	import uploadfileMixin from '@/mixin/uploadossfile.js';
	import deletefileMixin from '@/mixin/deleteossfile.js';
	//import getList from '../../utils/getlist.js';
	import {
		classifyListData,
		insertUploadImage,
		showUploadImage,
		deleteUploadImage
	}
	from '../../api/index';
	export default {
		filters: {
			formatStr(str) {
				if(str.length>10){
				return str.toString().substr(0, 10)+'...';}
				else{
			    return str;		
				}
			}},
		components: {

		},
		mixins: [uploadfileMixin,deletefileMixin],
		data() {
			return {
				dialogVisible: true,
				input1: "",
				input2:"",
				data: [],
				liststyle: 1,
				options: [{
					value: '选项1',
					label: '按文件名（a-z）'
				}, {
					value: '选项2',
					label: '按文件名（z-a）'
				}, {
					value: '选项3',
					label: '文件大小（大-小）'
				}, {
					value: '选项4',
					label: '文件大小（小-大）'
				}, {
					value: '选项5',
					label: '上传时间（新-旧）'
				},{
					value: '选项6',
					label: '上传时间（旧-新）'
				}
				],
				value: '',
				tableData: [{
						name: '图片1',
						time: '00:00:34',
						size: '1.7',
						date: '2016-05-03 00:00:00',
						src: 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png',
						resolution: '400*400'
					}
				],
				checkAll: false,
				multipleSelection: [],
				count: 0,
				progressFlag:false,
				loadProgress:[],
				nodedata:"",
				page:1,
				limit:10,
				total:0,
				node:'all',
				sortid:'',
				order:''
			}
		},
		methods: {
			showuploaddialog() {
				this.dialogVisible = true;
			},
			handleClose() {

			},
			handleNodeClick(data) {
				this.nodedata=data;
				this.page=1;
				if(data.pid==0){
				this.node='root';
				}else{
				this.node='children';
				}
				this.input2="";
				this.sortid=data.id
			    this.getImageData();
			},
			 handleSelect() {
				this.page=1;
				this.order=this.value;
				this.getImageData();
			 },
			handleSelectionChange(val) {
				this.multipleSelection = val;
				if (val.length == this.tableData.length) {
					this.checkAll = true;
				} else if (val.length == 0) {
					this.checkAll = false;
				}
			},
			allChoose(val) {
				if (val) {
					for (let i in this.tableData) {
						this.$nextTick(() => {
							this.$refs.multipleTable.toggleRowSelection(this.tableData[i], true);
						});
					}
				} else {
					this.$refs.multipleTable.clearSelection();
				}
			},
			handleSizeChange(val) {
				this.limit=val;
				this.getImageData();
			},
			handleCurrentChange(val) {
				this.page=val;
				this.getImageData();
			},
			handleCheckedCardsChange(value) {
				let checkedCount = value.length;
				this.checkAll = checkedCount === this.tableData.length;
			},
			clickliststyle() {
				if (this.liststyle) { //列表模式转卡片模式
					this.liststyle = false;
				} else {
					this.liststyle = true; //卡片模式转列表模式
					for (let i of this.multipleSelection) {
						this.$nextTick(() => {
							this.$refs.multipleTable.toggleRowSelection(i, true);
						});
					}
				}

			},
			handleCheckAllChange(val) {
				this.multipleSelection = val ? this.tableData : [];
			},
			condialogVisible() {
				console.log(this.multipleSelection);
			},
			getSortDir() {
				let shopuuid = localStorage.getItem('shopuuid');
				classifyListData({
					shopuuid
				}).then((res) => {
					var classifyList = res.data.list;
					for (let i = 0; i < classifyList.length; i++) {
						this.data.push({
							pid: '',
							id: '',
							label: '',
							children: []
						});
						this.data[i].pid = classifyList[i].pid;
						this.data[i].id = classifyList[i].id;
						this.data[i].label = classifyList[i].title;
						if (classifyList[i]._child) {
							for (let j = 0; j < classifyList[i]._child.length; j++) {
								this.data[i].children.push({
									pid: classifyList[i]._child[j].pid,
									id: classifyList[i]._child[j].id,
									label: classifyList[i]._child[j].title,
									plabel:classifyList[i].title
								});
							}
						}
					}
					//console.log(this.data);
				});

			},
			async getImageData(){
				let shopuuid=localStorage.getItem('shopuuid');
				var res=await showUploadImage({node:this.node,sortid:this.sortid,shopuuid,page:this.page,limit:this.limit,search:this.input2,order:this.order});
				this.tableData=res.data.imagedata;
				this.total=res.data.total;
			},
			filterNode(value, data) {
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
		   async selfile(e) {
			   if(!this.nodedata){
				   this.$message.error('请选择分类再上传！');
				   document.getElementById('upload').value="";
				   return;
			   }
			   if(this.nodedata.pid==0){
				   this.$message.error('请选择子分类上传，根目录不能上传！');
				   document.getElementById('upload').value="";
				   return;
			   }
				let files = e.target.files;
				this.count=files.length;
				let filearr=[];
				for (let i = 0; i < files.length; i++) {
					 const fileBase64 = await this.getBase64(files[i]);
					 const res = await this.getImgPx(fileBase64);
					 filearr[i]={
						name: files[i].name,
						size: (files[i].size / 1024 / 1024).toFixed(2),
						date: jsDateFormatter(new Date()),
						resolution:res.width + '*' + res.height,
						src:getObjectURL(files[i])
					};
					 this.tableData.splice(0,0,filearr[i]);
				}
				this.progressFlag=true;
				let username=localStorage.getItem('ms_username');
				let shopuuid=localStorage.getItem('shopuuid');
				let currentdir=this.nodedata.label;
				let parentdir=this.nodedata.plabel;
				//console.log(parentdir);
				let path='image/'+username+'/'+shopuuid+'/'+parentdir+'/'+currentdir+'/';
			    for(let j=0;j<files.length;j++){
				const tmpfile = files[j].name.split('.');
			    tmpfile.pop();
				let url=await this.fileUpload(files[j],path+tmpfile[0],j,this);
				filearr[j].src=url;
				let res=await  insertUploadImage ({file:JSON.stringify(filearr[j]),path,sortpid:this.nodedata.pid,sortid:this.nodedata.id,shopuuid});
					if(res.code==-1){
						let filepath=path+files[j].name;
						this.deleteMultiFile([filepath]);
						this.$message.error('保存数据库出错了！');
					}else if(res.code==-2){
						this.$message.error('请不要上传相同的文件');
					}
				}
			},
			getBase64(file) {
				const reader = new FileReader();
				reader.readAsDataURL(file);
				return new Promise((resolve) => {
					reader.onload = () => {
						resolve(reader.result);
					};
				});
			},
			getImgPx(img) {
				const image = new Image();
				image.src = img;
				return new Promise((resolve) => {
					image.onload = () => {
						const width = image.width;
						const height = image.height;
						resolve({
							width,
							height
						});
					};
				});
			},
			async deleteimage(){
				//console.log(this.multipleSelection);
				if(this.multipleSelection.length==0){
					this.$message.error("请选择文件后再来删除");
					return;
				}
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).then(async() =>{
							let pathname=[];
							let ids=[];
							for(let i=0;i<this.multipleSelection.length;i++){
								pathname.push(this.multipleSelection[i].path+this.multipleSelection[i].name);
								ids.push(this.multipleSelection[i].id);
								let index=this.tableData.indexOf(this.multipleSelection[i]);
								if(index>-1){
									this.tableData.splice(index,1);
								}
							}
							let deleteres=await deleteUploadImage({ids:ids.toString()});
							if(deleteres.code==1){
							   this.deleteMultiFile(pathname);
							}else{
							   this.$message.error('删除失败！');	
							}
						});
			},
			showallimage(){
				this.node='all';
				this.page=1;
				this.input2="";
				this.getImageData();
			},
			searchimagename(){
				this.page=1;
				this.getImageData();
			}
		},
		created() {
			this.getSortDir();
			this.page=1;
			this.getImageData();
			// let page = {
			// 	list: [],
			// 	total: 0
			// };
			// let opts = {
			// 	//delimiter: '/',
			// 	prefix: 'image/',
			// 	max_keys: 10,
			// 	marker: ''
			// };
			// getList(opts, page, this);
		},
		watch: {
			input1(val) {
				this.$refs.tree.filter(val);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.uploaddialog {
		.el-tree-node:focus>.el-tree-node__content {
			background-color: #409EFF;
			color: white;
		}
         
		.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
			background-color: #409EFF;
			color: white;
		}

		.uploadtop {
			border-top: 1px solid #eee;
			border-bottom: 1px solid #eee;
			line-height: 50px;
			margin-bottom: 10px;

			span {
				padding-left: 20px;
				padding-right: 10px;
				display: inline-block;
				line-height: 50px;

			}
		}

		.uploadbottom {

			width: 98%;
			height: 550px;
			display: flex;
			margin-left: 10px;

			.uploadleft {
				border: 1px solid #ccc;
				width: 25%;
				height: 550px;
				text-align: center;
             .showallbtn{
				 margin-top: 10px;
				 width: 100%;
				 border-left: none;
				 border-right:none;
			 }
				.searchinput1 {
					width: 90%;
					margin-top: 10px;
					display: inline-block;
				}

				.uploadtree {
					//padding-left: 10px;
					margin-top: 10px;

				}
			}

			.uploadright {
				margin-left: 15px;
				width: 75%;
				height: 550px;

				.uploadmaintop {
					height: 45px;
					width: 100%;
					line-height: 45px;
					position: relative;

					.el-menus {
						width: 160px;
						display: inline-block;
						margin-left: 3%;
					}

					.uploadqiehuan {
						line-height: 45px;
						margin-left: 25%;
						font-size: 22px;
						display: inline-block;
					}

					.searchinput2 {
						position: absolute;
						right: 0;
						width: 30%;
						margin-left: 1%;
						display: inline-block;
					}
				}

				.uploadmainfile {
					margin-top: 10px;

					.cardfile {
						height: 460px;
						overflow-y: scroll;

						.time {
							font-size: 13px;
							color: #999;
						}

						.bottom {
							margin-top: 13px;
							line-height: 12px;
						}

						.button {
							padding: 0;
							float: right;
						}

						.image {
							width: 100%;
							display: block;
						}

						.clearfix:before,
						.clearfix:after {
							display: table;
							content: "";
						}

						.clearfix:after {
							clear: both
						}
					}
				}

				.uploadmainbottom {
					margin-top: 10px;
					position: relative;
					height: 40px;

					.elcheckbox {
						position: absolute;
						left: 10px;
						top: 5px;
					}
					
					.deleteimage{
					    position:absolute;
						left:100px;
						top:5px;
					}

					.elpagination {
						position: absolute;
						right: 0;
					}
				}
			}
		}
	}
</style>
